/**
 * 食物分类数据更新脚本
 * 为现有食物分类添加order和isActive字段
 */

const mongoose = require('mongoose');
require('dotenv').config();

// 连接MongoDB
mongoose.connect(process.env.MONGODB_URL, {
  useNewUrlParser: true,
  useUnifiedTopology: true,
})
.then(() => console.log('已连接到MongoDB'))
.catch(err => {
  console.error('连接MongoDB失败:', err);
  process.exit(1);
});

// 食物分类模型（简化版本，仅用于脚本）
const foodCategorySchema = new mongoose.Schema({
  name: { type: String, required: true },
  description: { type: String },
  image: { type: String },
  isDeleted: { type: Boolean, default: false },
  order: { type: Number },
  isActive: { type: Boolean }
}, { timestamps: true });

const FoodCategory = mongoose.model('FoodCategory', foodCategorySchema);

// 更新现有食物分类数据
async function updateFoodCategories() {
  try {
    // 查找所有未删除的分类，不判断order和isActive是否存在
    const categories = await FoodCategory.find({ isDeleted: false });
    console.log(`找到${categories.length}个食物分类`);

    if (categories.length === 0) {
      console.log('没有找到需要更新的分类');
      process.exit(0);
    }

    // 更新所有找到的记录，无论它们是否已有这些字段
    let updateCount = 0;
    
    for (let i = 0; i < categories.length; i++) {
      const category = categories[i];
      
      // 显示更新前的分类信息
      console.log(`[更新前] 分类ID: ${category._id}, 名称: ${category.name}, order: ${category.order}, isActive: ${category.isActive}`);
      
      // 更新文档，强制设置字段
      const result = await FoodCategory.updateOne(
        { _id: category._id },
        { 
          $set: { 
            order: typeof category.order === 'number' ? category.order : i, 
            isActive: typeof category.isActive === 'boolean' ? category.isActive : true 
          } 
        }
      );

      if (result.modifiedCount > 0) {
        updateCount++;
      }
    }

    console.log(`成功更新了${updateCount}个分类记录`);

    // 显示更新后的分类信息
    const updatedCategories = await FoodCategory.find({ isDeleted: false });
    console.log('\n更新后的分类信息:');
    updatedCategories.forEach(cat => {
      console.log(`分类ID: ${cat._id}, 名称: ${cat.name}, order: ${cat.order}, isActive: ${cat.isActive}`);
    });

  } catch (error) {
    console.error('更新食物分类数据失败:', error);
  } finally {
    // 关闭数据库连接
    mongoose.connection.close();
    console.log('数据库连接已关闭');
  }
}

// 执行更新
console.log('开始更新食物分类数据...');
updateFoodCategories(); 